package com.example.learn.controller;

import com.example.learn.pojo.FrontKnow;
import com.example.learn.service.KnowldService;
import com.example.learn.service.SortService;
import com.example.learn.utils.R;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/know")
public class KnowldController {

    @Autowired
    KnowldService knowldService;

    @Autowired
    SortService sortService;

    @RequestMapping("/list")
    public R<Map> getKnowList() {
        List<FrontKnow> knowList = knowldService.getKnowleDgeList();
        Map dataMap = new HashMap();
        for (FrontKnow konw: knowList) {
            String sortName = sortService.getSortById(Integer.parseInt(konw.getSortId()));
            konw.setSortName(sortName);
        }
        dataMap.put("data", knowList);
        dataMap.put("total", knowList.size());
        return R.success(dataMap,"success");
    }

    @GetMapping("/select")
    public R<Map> getKnowById(@Param("id") String id) {
        FrontKnow know = knowldService.getKnowById(id);
        Map knowMap = new HashMap();
        knowMap.put("data", know);
        return R.success(knowMap,"success");
    }

    @PostMapping("/add")
    public R addKnow(@RequestBody FrontKnow know) {
        int count = knowldService.addKnowledge(know);
        if(count >= 1){
            return R.success("添加成功");
        }else {
            return R.failed("添加失败");
        }
    }

    @PostMapping("/update")
    public R updateKnow(@RequestBody FrontKnow know) {
        int count = knowldService.updateKnowledge(know);
        if(count >= 1){
            return R.success("修改成功");
        }else {
            return R.failed("修改失败");
        }
    }

    @GetMapping("/delete")
    public R delKnowById(String id) {
        int count = knowldService.delKnowById(id);
        if(count >= 1){
            return R.success("删除成功");
        }else {
            return R.failed("删除失败");
        }
    }
}
